#pragma once

#include <pthread.h>

namespace MutexModule
{
    class Mutex
    {
        Mutex(const Mutex &m) = delete;
        const Mutex &operator=(const Mutex &m) = delete;

    public:
        Mutex()
        {
            ::pthread_mutex_init(&_mutex, nullptr);
        }

        ~Mutex()
        {
            ::pthread_mutex_destroy(&_mutex);
        }

        void Lock()
        {
            ::pthread_mutex_lock(&_mutex);
        }

        void Unlock()
        {
            ::pthread_mutex_unlock(&_mutex);
        }

        pthread_mutex_t *LockAddr() { return &_mutex; }

    private:
        pthread_mutex_t _mutex;
    };

    class LockGuard
    {
    public:
        LockGuard(Mutex &mutex)
            : _mutex(mutex)
        {
            _mutex.Lock();
        }

        ~LockGuard()
        {
            _mutex.Unlock();
        }

    private:
        Mutex &_mutex; // 使用引用: 互斥锁不支持拷贝
    };
}